/*
 * Manager.cpp
 *
 *  Created on: Jan 24, 2015
 *      Author: wasp
 */

#include "Manager.hpp"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QDebug>
#include <bb/data/DataAccessError>
#include <bb/data/JsonDataAccess>
#include "../user/UserManager.hpp"
#include "../applicationui.hpp"
#include "Carrier.hpp"

namespace de
{
    namespace heimweghelden
    {
        namespace network
        {
            const QString BASEADDRESS = "http://192.168.1.108:3001";
            Manager* Manager::_instance = 0;
            Manager* Manager::getInstance(QObject* parent) {
                if (_instance == 0) {
                    _instance = new Manager(parent);
                }
                return _instance;
            }
            void Manager::drop() {
                if (_instance == 0) {
                    delete _instance;
                    _instance = 0;
                }
            }
            void Manager::publishUserinfo() {
                if (app == 0) { return; }
                QVariantMap data;
                data["phone"] = de::heimweghelden::user::UserManager::getInstance()->get(de::heimweghelden::user::UserManager::USERID);
                data["key"] = de::heimweghelden::user::UserManager::getInstance()->get(de::heimweghelden::user::UserManager::PUBKEY);
                //Carrier* carrier = new Carrier(METHOD::POST, this);


                QByteArray pdata;
                pdata.append("data=");
                bb::data::JsonDataAccess jda;
                jda.saveToBuffer(data, &pdata);


                QNetworkRequest request = QNetworkRequest();
                QString qurls(BASEADDRESS+"/helden/user/register");
                request.setUrl(QUrl(qurls));
                reply = app->networkmanager()->post(request, pdata);
                if (reply->isFinished()) {
                    onPublishUserinfoFinished();
                } else {
                    reply->connect
                    (
                            reply,
                            SIGNAL(finished()),
                            this,
                            SLOT(onPublishUserinfoFinished())
                    );
                }
            }

            Manager::Manager(QObject* parent) :
                        QObject(parent)
            {
                app = 0;
                reply = 0;
                if (parent != NULL) {
                    ApplicationUI* ui = reinterpret_cast<ApplicationUI*>(parent);
                    if (ui) {
                        app = ui;
                    }
                }
            }

            Manager::~Manager(){}

            void Manager::request(Carrier* carrier) {
                if (app == 0) { return; }
                QNetworkRequest request = QNetworkRequest();
                QByteArray pdata;
                QString query;
                bb::data::JsonDataAccess jda;
                QVariantMap data;
                QList<QString> keys = carrier->data()->keys();



                switch(carrier->method()) {
                    case POST:
                        request.setUrl(BASEADDRESS+carrier->methodurl);
                        foreach(const QString key, keys) {
                            data.insert(key, carrier->data()->value(key));
                        }
                        pdata.append("data=");
                        jda.saveToBuffer(data, &pdata);
                        carrier->setReply(app->networkmanager()->post(request, pdata));
                        break;
                    case GET:
                        if (carrier->data() != 0) {

                            foreach(const QString key, keys) {
                                query.append(key);
                                query.append("=");
                                query.append(carrier->data()->value(key).toString());
                                query.append("&");
                            }
                        }
                        request.setUrl(BASEADDRESS+carrier->methodurl+query);
                        carrier->setReply(app->networkmanager()->get(request));
                        break;
                }

                if (carrier->reply()->isFinished()) {
                    onPublishUserinfoFinished();
                } else {
                    carrier->reply()->connect
                    (
                            carrier->reply(),
                            SIGNAL(finished()),
                            carrier,
                            SLOT(onRequestFinished())
                    );
                }
            }

            void Manager::onPublishUserinfoFinished() {
                QString response;
                    if (reply) { // && reply->isFinished()
                        if (reply->error() == QNetworkReply::NoError) {
                            int available = reply->bytesAvailable();
                            if (available > 0) {
                                QByteArray buffer(reply->readAll());
                                response = QString::fromUtf8(buffer);
                            }
                        } else {
                            qDebug() << reply->errorString() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
                            response = "";
                        }

                        reply->deleteLater();
                    } else {
                        reply = NULL;
                        return;
                    }

                    if (response.trimmed().isEmpty()) {
                        response = "Unable to retrieve post response";
                        // TODO: meldung
                        reply = NULL;
                        return;
                    }

                    qDebug() << response;
                    //TODO:to be continued
                    // "{"success":true,"data":{"key":""},"message":"fertig"}"
                    /*bb::data::JsonDataAccess jda;
                    QVariant qtData = jda.loadFromBuffer(response);
                    if (jda.hasError()) {
                        bb::data::DataAccessError err = jda.error();
                        QString errorMsg = tr("Error converting JSON data: %1").arg(err.errorMessage());
                        qDebug() << errorMsg;
                        //TODO: fehlermeldung
                    } else {
                        //QVariantMap map = qtData.value<QVariantMap>();
                    }
                    reply = NULL;
                    */
            }

        } /* namespace network */
    } /* namespace heimweghelden */
} /* namespace de */
